/*
 * @Description: 序列管理
 * @Author: DSY
 * @Date: 2022-05-15 18:18:40
 * @LastEditors: DHL
 * @LastEditTime: 2022-06-15 11:02:09
 */

import { defineComponent, computed, onMounted, reactive, ref } from 'vue'
import { log } from '/@/utils/log'
import { ElMessage } from 'element-plus'
import { cloneDeep, assign } from 'lodash-es'
import { SequenceModel } from '/@/api/system/model/sequenceModel'
import { apiSequenceSave, apiSequenceUpdateById } from '/@/api/system/sequence'
import { dateFormat } from '/@/utils/dateUtils'

export default defineComponent({
  name: 'SequenceForm',
  emits: ['refreshTableData'],
  setup(props, { emit, expose }) {
    //////////////////////////////////////////////////
    // 属性
    //////////////////////////////////////////////////
    const dbFormRef = ref()
    const loading = ref(true)
    const codeExampleStr = ref('')

    /**
     * 表单操作标记
     */
    const action = ref('add')

    /**
     * 显示弹框
     */
    const visible = ref(false)

    /**
     * 标题
     */
    const title = computed(() => {
      let rtn = ''
      switch (action.value) {
        case 'add':
          rtn = '新增'
          break
        case 'edit':
          rtn = '编辑'
          break
        default:
          rtn = '查看'
          break
      }
      return rtn
    })

    /**
     * 公共
     */
    const myData = reactive({})

    //////////////////////////////////////////////////
    // 表单
    //////////////////////////////////////////////////

    const defaultForm = {
      id: '', // 编号
      name: '', // 名称
      code: '', // 编码
      prefix: '', // 前缀
      dateRule: '', // 日期规则
      seqCount: 0, // 序列位数
      seqStep: 1, // 步长
      splitCode: '', // 分隔符
      seqNext: 0, // 下一序列号
      currentCode: '', //
      autoRefresh: '1', // 是否自动刷新(1:刷新；2：不刷新)
      seq: 1
    }

    let dbForm = reactive<SequenceModel>(cloneDeep(defaultForm))

    //////////////////////////////////////////////////
    // 表单验证规则
    //////////////////////////////////////////////////

    /**
     * 表单验证规则
     */
    const rules = reactive({
      name: [
        {
          required: true,
          message: '请输入名称',
          trigger: 'blur'
        },
        {
          max: 50,
          message: '最多可输入50个字符',
          trigger: 'blur'
        }
      ],
      code: [
        {
          required: true,
          message: '请输入编码',
          trigger: 'blur'
        },
        {
          max: 50,
          message: '最多可输入50个字符',
          trigger: 'blur'
        }
      ],
      prefix: [
        {
          required: false,
          message: '请输入前缀',
          trigger: 'blur'
        },
        {
          max: 50,
          message: '最多可输入50个字符',
          trigger: 'blur'
        }
      ],
      dateRule: [
        {
          required: false,
          message: '请选择日期规则',
          trigger: 'blur'
        },
        {
          max: 50,
          message: '最多可输入50个字符',
          trigger: 'blur'
        }
      ],
      seqCount: [
        {
          required: false,
          message: '请输入序列位数',
          trigger: 'blur'
        }
      ],
      seqStep: [
        {
          required: false,
          message: '请输入步长',
          trigger: 'blur'
        }
      ],
      splitCode: [
        {
          required: false,
          message: '请选择分隔符',
          trigger: 'blur'
        },
        {
          max: 10,
          message: '最多可输入10个字符',
          trigger: 'blur'
        }
      ],
      seqNext: [
        {
          required: false,
          message: '请输入下一序列号',
          trigger: 'blur'
        }
      ],
      autoRefresh: [
        {
          required: true,
          message: '请选择是否自动刷新',
          trigger: 'blur'
        }
      ]
    })

    //////////////////////////////////////////////////
    // 函数
    //////////////////////////////////////////////////

    /**
     * 打开弹框
     */
    function handleOpen(actionParam: string, rowParam?: SequenceModel) {
      visible.value = true
      loading.value = false
      codeExampleStr.value = ''
      action.value = actionParam
      if (['edit', 'view'].indexOf(actionParam) > -1 && rowParam) {
        assign(dbForm, cloneDeep(rowParam))
        getExample()
      }
    }

    /**
     * 关闭弹框
     */
    function handleClose() {
      assign(dbForm, cloneDeep(defaultForm))
      visible.value = false
    }

    /**
     * 提交表单
     */
    function handleSubmit(isContinue: boolean) {
      dbFormRef.value.validate((valid: boolean) => {
        if (valid) {
          if (action.value === 'add') {
            addFun(isContinue)
          } else {
            editFun()
          }
        } else {
          log.warn('序列管理', '表单校验失败')
        }
      })
    }

    /**
     * 新增
     * @param isContinue 是否新增并继续
     */
    function addFun(isContinue: boolean) {
      loading.value = true
      apiSequenceSave(dbForm)
        .then((result) => {
          if (result?.success) {
            handleReset(!isContinue)
            ElMessage.success(result.message)
          } else {
            ElMessage.error(result?.message)
          }
        })
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 编辑
     * @returns
     */
    function editFun() {
      loading.value = true
      apiSequenceUpdateById(dbForm)
        .then((result) => {
          if (result?.success) {
            handleReset(true)
            ElMessage.success(result.message)
          } else {
            ElMessage.error(result?.message)
          }
        })
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 重置表单
     * @param isClosed 是否关闭弹框
     */
    function handleReset(isClosed: boolean) {
      assign(dbForm, cloneDeep(defaultForm))
      if (isClosed) {
        emit('refreshTableData')
        visible.value = false
      }
    }

    function getExample() {
      let prefix = ''
      if (dbForm.prefix) {
        prefix = dbForm.prefix
      }
      let sepCode = ''
      if (dbForm.splitCode) {
        sepCode = dbForm.splitCode
      }
      let dateStr = ''
      if (dbForm.dateRule) {
        let p = dbForm.dateRule
        if (p.indexOf('yyyy') >= 0) {
          p = p.replace('yyyy', '{y}')
        }
        if (p.indexOf('MM') >= 0) {
          p = p.replace('MM', '{m}')
        }
        if (p.indexOf('dd') >= 0) {
          p = p.replace('dd', '{d}')
        }
        dateStr = dateFormat(new Date(), dbForm.dateRule)
      }

      let seqStr = '1'
      for (let i = 1; i < dbForm.seqCount; i++) {
        seqStr = '0' + seqStr
      }
      codeExampleStr.value = prefix + sepCode + dateStr + sepCode + seqStr
    }

    /**
     * 暴露函数
     */
    expose({ handleOpen })

    return {
      loading,
      visible,
      action,
      title,
      myData,
      dbFormRef,
      dbForm,
      rules,
      handleOpen,
      handleClose,
      handleSubmit,
      handleReset,
      getExample,
      codeExampleStr
    }
  }
})
